package mc.support.crawler;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created with IntelliJ IDEA. <br/>
 * User: francis    <br/>
 * Date: 13-11-6    <br/>
 * Time: 17:28  <br/>
 */
public class Query {

    public static final String HTTP_PREFIX = "http://";

    public static final String HTTPS_PREFIX = "https://";

    public static final String DEFAULT_CHARSET = "utf-8";

    public static final String GB2312 = "gb2312";

    private String httpPrefix;

    private String host;

    private String path;

    private String urlCharset;

    private Map<String, String> queryMap;

    public Query(String host, Map<String, String> queryMap) {
        this( host, "", queryMap );
    }

    public Query(String host, String path, Map<String, String> queryMap) {
        this( HTTP_PREFIX, host, path, DEFAULT_CHARSET, queryMap );
    }

    public Query(String httpPrefix, String host, String path, String urlCharset,
                 Map<String, String> queryMap) {
        this.httpPrefix = httpPrefix;
        this.host = host;
        this.path = path;
        this.urlCharset = urlCharset;
        this.queryMap = queryMap;
    }

    public String getHttpPrefix() {
        return httpPrefix;
    }

    public void setHttpPrefix(String httpPrefix) {
        this.httpPrefix = httpPrefix;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getUrlCharset() {
        return urlCharset;
    }

    public void setUrlCharset(String urlCharset) {
        this.urlCharset = urlCharset;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Map<String, String> getQueryMap() {
        return queryMap;
    }

    public void setQueryMap(Map<String, String> queryMap) {
        this.queryMap = queryMap;
    }

    public String buildQueryURL() throws UnsupportedEncodingException {
        StringBuilder s = new StringBuilder();

        s.append( httpPrefix ).append( host );

        if ( path.startsWith( "/" ) ) {
            s.append( path ).append( '?' );
        } else {
            s.append( '/' ).append( path ).append( '?' );
        }

        for ( Map.Entry<String, String> e : queryMap.entrySet() ) {
            s.append( '&' ).append( e.getKey() )
                    .append( '=' ).append( encode( e.getValue(), urlCharset ) );
        }

        return s.toString();
    }

    private String encode(String s, String charset) throws UnsupportedEncodingException {
        return URLEncoder.encode( s, charset );
    }

}
